// 全选/取消全选功能
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.category-checkbox:not(:disabled)');
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
    });
    toggleBatchDeleteButton();
}

// 根据选中状态启用/禁用批量删除按钮
function toggleBatchDeleteButton() {
    const checkboxes = document.querySelectorAll('.category-checkbox:checked');
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    batchDeleteBtn.disabled = checkboxes.length === 0;
}

// 提交批量删除表单
function submitBatchDelete() {
    const checkboxes = document.querySelectorAll('.category-checkbox:checked');
    if (checkboxes.length === 0) {
        createNotification('请选择要删除的分类', 'error');
        return;
    }
    
    if (confirm('确定要删除选中的分类吗？删除后该分类下的链接将变为未分类。')) {
        const formData = new FormData();
        checkboxes.forEach(checkbox => {
            formData.append('category_ids', checkbox.value);
        });
        
        fetch('/admin/link-categories/batch-delete', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                createNotification(data.message, 'success');
                // 移除选中的行并添加动画效果
                checkboxes.forEach(checkbox => {
                    const row = checkbox.closest('tr');
                    row.style.transition = 'all 0.3s ease-out';
                    row.style.backgroundColor = '#ffdddd';
                    row.style.height = row.offsetHeight + 'px';
                    
                    // 延迟后隐藏行
                    setTimeout(() => {
                        row.style.opacity = '0';
                        row.style.height = '0';
                        row.style.margin = '0';
                        row.style.padding = '0';
                        
                        // 再延迟后从DOM中移除
                        setTimeout(() => {
                            row.remove();
                            
                            // 如果没有行了，更新界面
                            if (document.querySelectorAll('tbody tr').length === 0) {
                                document.querySelector('.card-body').innerHTML = `
                                    <div style="text-align: center; padding: 40px; color: #666;">
                                        <p>暂无分类，请点击上方"添加分类"按钮添加</p>
                                    </div>
                                `;
                            }
                        }, 300);
                    }, 100);
                });
                
                // 重置全选框和批量删除按钮
                document.getElementById('selectAll').checked = false;
                toggleBatchDeleteButton();
            } else {
                createNotification(data.message, 'error');
            }
        })
        .catch(error => {
            createNotification('删除失败，请重试', 'error');
        });
    }
}

// 页面加载完成后添加事件监听器
document.addEventListener('DOMContentLoaded', function() {
    // 为全选框添加事件监听
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', toggleSelectAll);
    }
    
    // 为所有非禁用的复选框添加事件监听
    const checkboxes = document.querySelectorAll('.category-checkbox:not(:disabled)');
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', toggleBatchDeleteButton);
    });
    
    // 为批量删除按钮添加事件监听
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    if (batchDeleteBtn) {
        batchDeleteBtn.addEventListener('click', submitBatchDelete);
    }
    
    // 添加删除按钮点击事件
    document.querySelectorAll('.delete-btn').forEach(button => {
        button.addEventListener('click', function() {
            const categoryId = this.getAttribute('data-id');
            if (confirm('确定要删除这个分类吗？删除后该分类下的链接将变为未分类。')) {
                // 找到当前行
                const row = this.closest('tr');
                
                // 发送删除请求
                fetch(`/admin/link-categories/delete/${categoryId}`, {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        createNotification(data.message, 'success');
                        
                        // 添加删除动画
                        row.style.transition = 'all 0.3s ease-out';
                        row.style.backgroundColor = '#ffdddd';
                        row.style.height = row.offsetHeight + 'px';
                        
                        // 延迟后隐藏行
                        setTimeout(() => {
                            row.style.opacity = '0';
                            row.style.height = '0';
                            row.style.margin = '0';
                            row.style.padding = '0';
                            
                            // 再延迟后从DOM中移除
                            setTimeout(() => {
                                row.remove();
                                
                                // 如果没有行了，更新界面
                                if (document.querySelectorAll('tbody tr').length === 0) {
                                    document.querySelector('.card-body').innerHTML = `
                                        <div style="text-align: center; padding: 40px; color: #666;">
                                            <p>暂无分类，请点击上方"添加分类"按钮添加</p>
                                        </div>
                                    `;
                                }
                            }, 300);
                        }, 100);
                    } else {
                        createNotification(data.message, 'error');
                    }
                })
                .catch(error => {
                    createNotification('删除失败，请重试', 'error');
                });
            }
        });
    });
    
    // 初始化状态切换功能
    setupStatusToggleButtons();
});

// 通知函数
function createNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = 'notification';
    
    // 设置样式
    notification.style.position = 'fixed';
    notification.style.top = '20px';
    notification.style.right = '20px';
    notification.style.padding = '15px 20px';
    notification.style.borderRadius = '5px';
    notification.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.1)';
    notification.style.zIndex = '10000';
    notification.style.transition = 'all 0.3s ease';
    notification.style.opacity = '0';
    notification.style.transform = 'translateY(-20px)';
    notification.style.fontSize = '14px';
    notification.style.fontWeight = '500';
    notification.style.color = 'white';
    
    // 根据类型设置背景色
    switch (type) {
        case 'success':
            notification.style.backgroundColor = '#2ecc71';
            break;
        case 'error':
            notification.style.backgroundColor = '#e74c3c';
            break;
        case 'warning':
            notification.style.backgroundColor = '#f39c12';
            break;
        default:
            notification.style.backgroundColor = '#3498db';
    }
    
    // 设置消息内容
    notification.textContent = message;
    
    // 添加到文档中
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.style.opacity = '1';
        notification.style.transform = 'translateY(0)';
    }, 10);
    
    // 自动关闭
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateY(-20px)';
        
        // 移除元素
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 设置状态切换按钮功能
function setupStatusToggleButtons() {
    // 为所有状态切换按钮添加事件监听
    document.querySelectorAll('.toggle-status-btn').forEach(button => {
        button.addEventListener('click', function() {
            // 获取分类ID和当前状态
            const categoryId = this.getAttribute('data-id');
            const currentStatus = this.getAttribute('data-status');
            
            // 确认状态切换操作
            const newStatus = currentStatus === '1' ? '0' : '1';
            const confirmMessage = currentStatus === '1' ? '确定要禁用这个分类吗？禁用后该分类下的链接仍会保留，但不会显示在分类列表中。' : '确定要启用这个分类吗？';
            
            if (confirm(confirmMessage)) {
                // 禁用按钮并显示加载状态
                this.disabled = true;
                const originalText = this.textContent;
                this.textContent = '处理中...';
                
                // 发送状态切换请求
                fetch(`/admin/link-categories/toggle-status/${categoryId}`, {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    // 恢复按钮可用状态
                    this.disabled = false;
                    
                    if (data.success) {
                        // 使用后端返回的new_status更新按钮状态（转换为字符串格式）
                        const backendNewStatus = data.new_status ? '1' : '0';
                        this.setAttribute('data-status', backendNewStatus);
                        
                        // 更新按钮样式和文本
                        if (backendNewStatus === '1') {
                            this.className = 'btn btn-xs btn-warning toggle-status-btn';
                            this.textContent = '禁用';
                        } else {
                            this.className = 'btn btn-xs btn-success toggle-status-btn';
                            this.textContent = '启用';
                        }
                        
                        // 更新状态文本（找到按钮前面的span元素）
                        const statusTd = this.closest('td');
                        const statusSpans = statusTd.querySelectorAll('span');
                        if (statusSpans.length > 0) {
                            const statusText = statusSpans[0]; // 获取第一个span元素作为状态文本
                            if (backendNewStatus === '1') {
                                statusText.textContent = '启用';
                                statusText.style.color = '#2ecc71';
                            } else {
                                statusText.textContent = '禁用';
                                statusText.style.color = '#e74c3c';
                            }
                        }
                        
                        // 显示成功通知
                        createNotification(data.message || '状态更新成功', 'success');
                    } else {
                        this.textContent = originalText;
                        createNotification(data.message, 'error');
                    }
                })
                .catch(error => {
                    // 恢复按钮状态
                    this.disabled = false;
                    this.textContent = originalText;
                    createNotification('状态切换失败，请重试', 'error');
                });
            }
        });
    });
}